package com.example.ecommercemarketing.handler.impl;

import com.example.ecommercemarketing.dto.MarketingElementsDTO;
import com.example.ecommercemarketing.dto.ProductDTO;
import com.example.ecommercemarketing.dto.UserDTO;
import com.example.ecommercemarketing.handler.MarketingElementsHandler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 老客复购榜处理器（面向注册超过90天的用户）
 * 榜单规则：老客户复购率最高的商品TOP100
 */
public class LoyalCustomerRepurchaseHandler implements MarketingElementsHandler {

    private static final List<String> LOYAL_CUSTOMER_PRODUCTS = Arrays.asList(
            "2002", "2008", "2015", "1324", "2452" // 实际应从数据分析系统获取
    );

    @Value("${marketing.loyalCustomerRank.url:/rank/loyal-customer}")
    private String rankPageUrl;

    @Override
    public MarketingElementsDTO handle(ProductDTO product, UserDTO user) {
        // 仅对老客生效
        if (isNewCustomer(user)) {
            return null;
        }

        if (!LOYAL_CUSTOMER_PRODUCTS.contains(String.valueOf(product.getId()))) {
            return null;
        }

        //这里直接写死了一些测试数据，实际项目中是通过发其它应用的接口、查数据库、经过一些繁琐的业务逻辑处理来获取数据的
        MarketingElementsDTO elements = new MarketingElementsDTO();
        elements.setRecommendText(String.format("【老客复购】%s，回头客复购率高达75%%", product.getName()));
        elements.setProductHighlights("90%老用户二次购买");
        elements.setMarketingImageUrl("https://cdn.example.com/ranks/loyal-customer/" + product.getId() + ".jpg");
        elements.setExtraInfo(String.format("<a href='%s' target='_blank'>老客复购榜></a>", rankPageUrl));
        elements.setSource("loyal_customer_rank");

        Random random = new Random();
        int randomTime = random.nextInt(15);
        //模拟实际业务中的耗时
        try {
            TimeUnit.MILLISECONDS.sleep(randomTime);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        return elements;
    }

    private boolean isNewCustomer(UserDTO user) {
        return user.getUserId() != null && user.getUserId() % 3 == 0;
    }
}